// services/console.ts - 控制台管理 API 服务
import apiClient from './api';
import type { ConsoleInfo } from '../types/api';

/**
 * 获取 VNC 控制台信息
 * @param connection 连接ID
 * @param name 虚拟机名称
 */
export const getVNCInfo = async (
  connection: string,
  name: string
): Promise<ConsoleInfo> => {
  const response = await apiClient.get<ConsoleInfo>('/console/vnc/info', {
    params: { connection, name },
  });
  return response.data;
};

/**
 * 获取 SPICE 控制台信息
 * @param connection 连接ID
 * @param name 虚拟机名称
 */
export const getSPICEInfo = async (
  connection: string,
  name: string
): Promise<ConsoleInfo> => {
  const response = await apiClient.get<ConsoleInfo>('/console/spice/info', {
    params: { connection, name },
  });
  return response.data;
};

/**
 * 获取串口控制台信息
 * @param connection 连接ID
 * @param name 虚拟机名称
 */
export const getSerialInfo = async (
  connection: string,
  name: string
): Promise<ConsoleInfo> => {
  const response = await apiClient.get<ConsoleInfo>('/console/serial/info', {
    params: { connection, name },
  });
  return response.data;
};

/**
 * 获取控制台 WebSocket URL
 * @param connection 连接ID
 * @param name 虚拟机名称
 * @param type 控制台类型
 * @param token 认证令牌
 */
export const getConsoleWebSocketUrl = (
  connection: string,
  name: string,
  type: 'vnc' | 'spice' | 'serial',
  token?: string
): string => {
  const baseUrl = import.meta.env.VITE_API_BASE_URL || 'http://localhost:8080/api/v1';
  const wsBaseUrl = baseUrl.replace('http://', 'ws://').replace('https://', 'wss://');

  const params = new URLSearchParams({
    connection,
    name,
    ...(token && { token }),
  });

  return `${wsBaseUrl}/console/${type}?${params.toString()}`;
};

// 导出所有服务
export const consoleService = {
  getVNCInfo,
  getSPICEInfo,
  getSerialInfo,
  getConsoleWebSocketUrl,
};